package com.uubx.interceptor;

import com.uubx.exception.CustomerException;
import com.uubx.pojo.Menu;
import com.uubx.pojo.Permission;
import com.uubx.pojo.User;
import com.uubx.result.MessageCode;
import com.uubx.result.Result;
import com.uubx.result.ResultUtils;
import com.uubx.service.UserService;
import com.uubx.utils.JedisTemplete;
import com.uubx.utils.JsonUtils;
import com.uubx.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author wuguojun
 * @Date 2021/1/5 16:08
 * @Version 1.0
 */
public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisTemplete jedisTemplete;

    public static final String LOGIN="xasfasfcsdcdsadacjsdj";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //用户访问地址
        String url=request.getRequestURI();

        //从redis中取出权限信息
        //获取到token
        String token = request.getHeader("token");
        String userJson = jedisTemplete.get(LOGIN + token);
        if (userJson==null){
            throw new CustomerException(MessageCode.REDIS_IS_EMPTY);
        }
        User activeUser = JsonUtils.jsonToPojo(userJson, User.class);

//        //取出session中权限url
//        //获取用户操作权限
        List<Permission> permissionList = activeUser.getPermissions();
        for (Permission permission:permissionList){
            String permissionUrl = permission.getUrl();
            if (url.contains(permissionUrl)){
                return true;
            }
        }
//        Result result=ResultUtils.buildFail(66666,"当前用户无权限访问该资源");
//        ResponseUtils.responseJson(response,JsonUtils.objectToJson(result));
        return false;


    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
